package com.slingshot.identitysdk

import android.Manifest
import android.arch.lifecycle.ViewModelProviders
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.widget.Toast
import com.liushiyu.tooltip.Tooltip
import com.slingshot.identitylibrary.Slingshot
import com.slingshot.identitylibrary.scan.callback.IDScanCallback
import com.slingshot.identitylibrary.scan.data.IdData
import com.slingshot.identitysdk.base.BaseActivity
import com.slingshot.identitysdk.common.SlingshotData
import com.slingshot.identitysdk.util.PhotoUtil
import com.slingshot.identitysdk.viewmodel.SlingshotViewModel
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : BaseActivity() {

    companion object {
        const val INTENT_CODE = 1000

        private val NEEDED_PERMISSIONS_REGISTER: Array<String> = arrayOf(
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
    }

    private lateinit var slingshotViewModel: SlingshotViewModel

    private var loadingDialog = Tooltip.loading().message("正在扫描..").build()

    private lateinit var photoUtil : PhotoUtil

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        checkFirstStart()
    }

    private fun checkFirstStart() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!NEEDED_PERMISSIONS_REGISTER.checkPermissions()) {
                requestPermissions(NEEDED_PERMISSIONS_REGISTER, INTENT_CODE)
                return
            }
        }
        init()
    }

    private fun Array<String>.checkPermissions(): Boolean {
        var allGranted = true
        for (neededPermission in this) {
            allGranted = allGranted and (ContextCompat.checkSelfPermission(
                this@MainActivity,
                neededPermission
            ) == PackageManager.PERMISSION_GRANTED)
        }
        return allGranted
    }

    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        var isAllGranted = true
        for (grantResult in grantResults) {
            isAllGranted = isAllGranted and (grantResult == PackageManager.PERMISSION_GRANTED)
        }
        afterRequestPermission(requestCode, isAllGranted)
    }

    private fun afterRequestPermission(requestCode: Int, isAllGranted: Boolean) {
        if (requestCode == INTENT_CODE) {
            if (isAllGranted) {
                init()
            } else {
                Toast.makeText(this, "权限被拒绝", Toast.LENGTH_LONG).show()
            }
        }
    }

    private fun init() {
        // 初始化弹弓SDK
        Slingshot.init(this, "e97812ef73628fe7cd2c4eb9288d65e1", "c57950ae048a633f216ed0a2797ed156")

        slingshotViewModel = ViewModelProviders.of(this).get(SlingshotViewModel::class.java)
        mainTopView.init(this, slingshotViewModel)
        photoUtil = PhotoUtil()
        photoUtil.init(this, slingshotViewModel)

        initClickListener()
    }

    private fun initClickListener() {
        clearInfoButton.setOnClickListener {
            clearInfoButtonClick()
        }
        idScanButton.setOnClickListener {
            idScanButtonClick()
        }
        extractIdCardFrontButton.setOnClickListener {
            extractIdCardFrontButtonClick()
        }
        extractIdCardBackButton.setOnClickListener {
            extractIdCardBackButtonClick()
        }
        extractFaceDetectButton.setOnClickListener {
            extractFaceDetectButtonClick()
        }
    }

    /**
     * 清除页面数据
     * */
    private fun clearInfoButtonClick() {
        val data = SlingshotData(0, null, null)
        slingshotViewModel.setSlingshotData(data)
    }

    /**
     * 扫描 身份证
     * */
    private fun idScanButtonClick() {
        Slingshot.idScanAgent().setTimeout(5000).scanIdStart(object : IDScanCallback {

            override fun scanStart() {
                super.scanStart()
                loadingDialog = Tooltip.loading().message("正在扫描..").build()
                loadingDialog.show(supportFragmentManager, "idScan")
            }

            override fun scanSuccess(idData: IdData) {
                val data = SlingshotData(1, "$idData", idData.userBitmap)
                slingshotViewModel.setSlingshotData(data)
            }

            override fun scanFail(errorCode: Int) {
                val data = SlingshotData(2, "扫描失败 errorCode = $errorCode", null)
                slingshotViewModel.setSlingshotData(data)
            }

            override fun scanFinish() {
                super.scanFinish()
                loadingDialog.dismiss()
            }
        })
    }

    /**
     * 获取 身份证正面 信息
     * */
    private fun extractIdCardFrontButtonClick() {
        photoUtil.scanIdentityNationalEmblem()
    }

    /**
     * 获取 身份证背面 信息
     * */
    private fun extractIdCardBackButtonClick() {
        photoUtil.scanIdentityFace()
    }

    /**
     * 获取 人物 信息
     * */
    private fun extractFaceDetectButtonClick() {
        photoUtil.extractFaceDetect()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        photoUtil.onActivityResult(requestCode, resultCode, data)
    }

    override fun onDestroy() {
        super.onDestroy()
        Slingshot.release()
    }
}
